﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
//using SerialPortHelperLib;
using System.Threading;
using System.Configuration;
using XChipTool.Enties;
using XChip_Common;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_CMX : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;

        float[,] m_fDMatrix = new float[3, 3];
        float[,] m_fAMatrix = new float[3, 3];
        float[,] m_fCMatrix = new float[3, 3];

        long[] m_nSymbol = new long[3];
        /// <summary>
        /// 设置点击那个文本框设置值
        /// </summary>
        int m_nSelMatrix = 0;
        private bool isWrite = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipCMX;

        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        public XChip_CMX()
        {
            InitializeComponent();
        }
        public XChip_CMX(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            aBll = _aBll;
            XChipCMX = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "cmx" || c.Classify == "Common"));
            InitializeComponent();
        }

        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            try
            {
                WaitBefore.Start("读取中", "正在加载中", 10);
                isRead = true;

                if ((await GetCMXRegister("AutoFactor_en") & 0x01) == 1)
                {
                    AutoFactor_en.CheckState = CheckState.Checked;
                }
                else
                {
                    AutoFactor_en.CheckState = CheckState.Unchecked;
                }
                if ((await GetCMXRegister("AutoCT_en") & 0x02) == 2)
                {
                    AutoCT_en.CheckState = CheckState.Checked;
                }
                else
                {
                    AutoCT_en.CheckState = CheckState.Unchecked;
                }

                Max_factor.Text = (await GetCMXRegister("Max_factor")).ToString("X2");
                Min_factor.Text = (await GetCMXRegister("Min_factor")).ToString("X2");

                Max_gain.Text = (await GetCMXRegister("Max_gain")).ToString("X2");
                Min_gain.Text = (await GetCMXRegister("Min_gain")).ToString("X2");


                CT_list0.Text = ((await GetCMXRegister("CT_list0_h") & 0x3) << 8 | await GetCMXRegister("CT_list0_l")).ToString("X3");
                CT_list1.Text = ((await GetCMXRegister("CT_list1_h") & 0x3) << 8 | await GetCMXRegister("CT_list1_l")).ToString("X3");
                CT_list2.Text = ((await GetCMXRegister("CT_list2_h") & 0x3) << 8 | await GetCMXRegister("CT_list2_l")).ToString("X3");

                float fValue1, fValue2;
                bool bState;
                for (int i = 0; i < 3; i++)//这里的3 表示 DAC//012
                {
                    char mask = '\0';
                    switch (i)
                    {
                        case 0:
                            mask = 'D';
                            break;
                        case 1:
                            mask = 'A';
                            break;
                        case 2:
                            mask = 'C';
                            break;
                        default:
                            break;

                    }

                    var nSymbol = await GetCMXRegister($"Matrix_{mask}");// SerialSend.ReadRegister((ulong)(0x80300000|0x122e)+ (ulong)i, sPortTemp);
                                                                   //这个方法设置acd
                    SetSymbol((int)nSymbol, i);
                    var nHigh = await GetCMXRegister($"Matrix_{mask}_8_h");//SerialSend.ReadRegister((ulong)(0x80300000 | 0x1200) + (ulong)(i * 12), sPortTemp);
                    var nLow = await GetCMXRegister($"Matrix_{mask}_8_l");//SerialSend.ReadRegister((ulong)(0x80300000 | 0x1201) + (ulong)(i * 12), sPortTemp);
                    fValue1 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 0);
                    if (!bState) { fValue1 = -fValue1; }
                    SetMatrix(fValue1, 8, i); //设置8位 这里的i 表示 i= 0 表示D i= 1 表示A i= 2 表示C

                    nHigh = await GetCMXRegister($"Matrix_{mask}_7_h");
                    nLow = await GetCMXRegister($"Matrix_{mask}_7_l");
                    fValue2 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 1);
                    if (!bState) { fValue2 = -fValue2; }
                    SetMatrix(fValue2, 7, i);//设置7位
                    SetMatrix(1 - fValue1 - fValue2, 9, i);//设置9位

                    nHigh = await GetCMXRegister($"Matrix_{mask}_6_h");
                    nLow = await GetCMXRegister($"Matrix_{mask}_6_l");
                    fValue1 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 2);
                    if (!bState) { fValue1 = -fValue1; }
                    SetMatrix(fValue1, 6, i);//设置6位

                    nHigh = await GetCMXRegister($"Matrix_{mask}_4_h");
                    nLow = await GetCMXRegister($"Matrix_{mask}_4_l");
                    fValue2 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 3);
                    if (!bState) { fValue2 = -fValue2; }
                    SetMatrix(fValue2, 4, i);//设置4位
                    SetMatrix(1 - fValue2 - fValue1, 5, i);//设置5位

                    nHigh = await GetCMXRegister($"Matrix_{mask}_3_h");
                    nLow = await GetCMXRegister($"Matrix_{mask}_3_l");
                    fValue1 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 4);
                    if (!bState) { fValue1 = -fValue1; }
                    SetMatrix(fValue1, 3, i);//设置3位

                    nHigh = await GetCMXRegister($"Matrix_{mask}_2_h");
                    nLow = await GetCMXRegister($"Matrix_{mask}_2_l");
                    fValue2 = (nLow + nHigh * 256) / 1024.0f;
                    bState = GetBitState((int)nSymbol, 5);
                    if (!bState) { fValue2 = -fValue2; }
                    SetMatrix(fValue2, 2, i); //设置2位
                    SetMatrix(1 - fValue2 - fValue1, 1, i);//设置1位

                }
                if (sewenRadio.SelectedIndex == -1) sewenRadio.SelectedIndex = 0;
                sewenRadio_SelectedIndexChanged(null, null);
                isRead = true;//sewenRadio改变完后置了false,所以这里还需置回true
                simpleButton2_Click(null, null);
                simpleButton3_Click(null, null);
                btn_Get_scene_Click(null, null);
                isRead = true;
                isRead = false;

                if (CMX_MATRIX2.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX2);
                }
                else if (CMX_MATRIX3.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX3);
                }
                else if (CMX_MATRIX6.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX6);
                }
                else if (CMX_MATRIX4.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX4);
                }
                else if (CMX_MATRIX7.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX7);
                }
                else if (CMX_MATRIX8.BackColor == Color.LightPink)
                {
                    SetCmxTxt(CMX_MATRIX8);
                }
                WaitBefore.Close();
            }
            catch (Exception ex)
            {
                WaitBefore.Close();
                throw;
            }

        }
        void SetSymbol(int symbol, int light)
        {
            switch (light)
            {
                case 1://A
                    m_nSymbol[0] = symbol;
                    break;
                case 2://C
                    m_nSymbol[1] = symbol;
                    break;
                default://D
                    m_nSymbol[2] = symbol;
                    break;
            }
        }

        void SetMatrix(float value, int n, int nLight)
        {
            switch (nLight)
            {
                case 0: //d
                    {
                        switch (n)
                        {
                            case 1: m_fDMatrix[0, 0] = value; break;
                            case 2: m_fDMatrix[0, 1] = value; break;
                            case 3: m_fDMatrix[0, 2] = value; break;
                            case 4: m_fDMatrix[1, 0] = value; break;
                            case 5: m_fDMatrix[1, 1] = value; break;
                            case 6: m_fDMatrix[1, 2] = value; break;
                            case 7: m_fDMatrix[2, 0] = value; break;
                            case 8: m_fDMatrix[2, 1] = value; break;
                            case 9: m_fDMatrix[2, 2] = value; break;
                            default:
                                break;
                        }

                    }
                    break;
                case 1://a
                    {
                        switch (n)
                        {
                            case 1: m_fAMatrix[0, 0] = value; break;
                            case 2: m_fAMatrix[0, 1] = value; break;
                            case 3: m_fAMatrix[0, 2] = value; break;
                            case 4: m_fAMatrix[1, 0] = value; break;
                            case 5: m_fAMatrix[1, 1] = value; break;
                            case 6: m_fAMatrix[1, 2] = value; break;
                            case 7: m_fAMatrix[2, 0] = value; break;
                            case 8: m_fAMatrix[2, 1] = value; break;
                            case 9: m_fAMatrix[2, 2] = value; break;
                            default:
                                break;
                        }

                    }
                    break;
                case 2://c
                    {
                        switch (n)
                        {
                            case 1: m_fCMatrix[0, 0] = value; break;
                            case 2: m_fCMatrix[0, 1] = value; break;
                            case 3: m_fCMatrix[0, 2] = value; break;
                            case 4: m_fCMatrix[1, 0] = value; break;
                            case 5: m_fCMatrix[1, 1] = value; break;
                            case 6: m_fCMatrix[1, 2] = value; break;
                            case 7: m_fCMatrix[2, 0] = value; break;
                            case 8: m_fCMatrix[2, 1] = value; break;
                            case 9: m_fCMatrix[2, 2] = value; break;
                            default:
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        bool GetBitState(int value, int index)
        {
            bool bRet = false;
            if (((value >> (5 - index)) & 0x01) > 0)
            {
                bRet = true;
            }
            return bRet;
        }

        /// <summary>
        /// 设置文本框值
        /// </summary>
        /// <param name="m_Mat"></param>
        void SetCmxMatrixTxt(float[,] m_Mat)
        {
            CMX_MATRIX1.Text = m_Mat[0, 0].ToString("f6");
            CMX_MATRIX2.Text = m_Mat[0, 1].ToString("f6");
            CMX_MATRIX3.Text = m_Mat[0, 2].ToString("f6");

            CMX_MATRIX4.Text = m_Mat[1, 0].ToString("f6");
            CMX_MATRIX5.Text = m_Mat[1, 1].ToString("f6");
            CMX_MATRIX6.Text = m_Mat[1, 2].ToString("f6");

            CMX_MATRIX7.Text = m_Mat[2, 0].ToString("f6");
            CMX_MATRIX8.Text = m_Mat[2, 1].ToString("f6");
            CMX_MATRIX9.Text = m_Mat[2, 2].ToString("f6");
        }


        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            Real_gain.Text = ((await GetCMXRegister("Real_gain_h") << 8) & 0x1f00 | await GetCMXRegister("Real_gain_l")).ToString("X2");
            //by 20200919 shaoyidong
        }

        private async void simpleButton3_Click(object sender, EventArgs e)
        {

            long nRGain, nBGain, nCList;

            nRGain = (await GetCMXRegister("CLIST(nRGain)_h") << 8) & 0xff00 | await GetCMXRegister("CLIST(nRGain)_l");
            nBGain = (await GetCMXRegister("CLIST(nBGain)_h") << 8) & 0xff00 | await GetCMXRegister("CLIST(nBGain)_l");
            if (nRGain > 0)
            {
                nCList = nBGain * 128 / nRGain;
                Cur_CT_value.Text = nCList.ToString("X2");
            }
        }
        void FactorGainShowHide(bool isbool)
        {
            Max_factor.Enabled = isbool;
            Min_factor.Enabled = isbool;

            Max_gain.Enabled = isbool;
            Min_gain.Enabled = isbool;
        }
        #region 色温选择

        private void CMX_CTLIST0_EditValueChanged(object sender, EventArgs e)
        {

        }
        #endregion

        private async Task SetCmxRegister(string nameType, ulong add)
        {
            bool success = await WriteRegisterAsync(XChipCMX.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCmxRegister 写入失败 - 地址: {XChipCMX.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address}, 值: {add:X}");
            }
        }
        private async Task SetCmxRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCmxRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }
        #region 点击radio  ACD  选择

        /// <summary>
        /// 点击acd 显示不同的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sewenRadio_SelectedIndexChanged(object sender, EventArgs e)
        {
            //点击显示不同的值
            isRead = true;
            switch (sewenRadio.SelectedIndex)
            {
                case 0://a
                    SetCmxMatrixTxt(m_fAMatrix);
                    break;
                case 1://c
                    SetCmxMatrixTxt(m_fCMatrix);
                    break;
                case 2://d
                    SetCmxMatrixTxt(m_fDMatrix);
                    break;
                default:
                    break;
            }
            isRead = false;
        }

        #endregion

        #region 文本框点击获取焦点 设置滚动条
        private void CMX_MATRIX2_Enter(object sender, EventArgs e)
        {
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            SetCmxTxt(txtedit);
        }

        private void SetCmxTxt(TextEdit txtedit)
        {
            m_nSelMatrix = int.Parse(txtedit.Tag.ToString());
            SetBackColorMatrix(m_nSelMatrix);
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            trackTxt.Text = Math.Abs(float.Parse(txtedit.Text)).ToString("f6");
            CMX_HIGH_PRE.Value = (int)(float.Parse(trackTxt.Text) * 100000);
        }
        private void CMX_MATRIX2_Click(object sender, EventArgs e)
        {

        }
        void SetBackColorMatrix(int m_nSelMatrix)
        {
            switch (m_nSelMatrix)
            {
                case 2:
                    CMX_MATRIX2.BackColor = Color.LightPink;
                    CMX_MATRIX3.BackColor = Color.White;
                    CMX_MATRIX6.BackColor = Color.White;
                    CMX_MATRIX4.BackColor = Color.White;
                    CMX_MATRIX7.BackColor = Color.White;
                    CMX_MATRIX8.BackColor = Color.White;
                    break;
                case 3:
                    CMX_MATRIX2.BackColor = Color.White;
                    CMX_MATRIX3.BackColor = Color.LightPink;
                    CMX_MATRIX6.BackColor = Color.White;
                    CMX_MATRIX4.BackColor = Color.White;
                    CMX_MATRIX7.BackColor = Color.White;
                    CMX_MATRIX8.BackColor = Color.White;
                    break;
                case 4:
                    CMX_MATRIX2.BackColor = Color.White;
                    CMX_MATRIX3.BackColor = Color.White;
                    CMX_MATRIX6.BackColor = Color.White;
                    CMX_MATRIX4.BackColor = Color.LightPink;
                    CMX_MATRIX7.BackColor = Color.White;
                    CMX_MATRIX8.BackColor = Color.White;
                    break;
                case 6:
                    CMX_MATRIX2.BackColor = Color.White;
                    CMX_MATRIX3.BackColor = Color.White;
                    CMX_MATRIX6.BackColor = Color.LightPink;
                    CMX_MATRIX4.BackColor = Color.White;
                    CMX_MATRIX7.BackColor = Color.White;
                    CMX_MATRIX8.BackColor = Color.White;
                    break;
                case 7:
                    CMX_MATRIX2.BackColor = Color.White;
                    CMX_MATRIX3.BackColor = Color.White;
                    CMX_MATRIX6.BackColor = Color.White;
                    CMX_MATRIX4.BackColor = Color.White;
                    CMX_MATRIX7.BackColor = Color.LightPink;
                    CMX_MATRIX8.BackColor = Color.White;
                    break;
                case 8:
                    CMX_MATRIX2.BackColor = Color.White;
                    CMX_MATRIX3.BackColor = Color.White;
                    CMX_MATRIX6.BackColor = Color.White;
                    CMX_MATRIX4.BackColor = Color.White;
                    CMX_MATRIX7.BackColor = Color.White;
                    CMX_MATRIX8.BackColor = Color.LightPink;
                    break;
                default:
                    break;
            }
        }
        void SetCMX_HIGH_PREPro(float fValue)
        {
            //这里是给滑动条赋初始值值
            CMX_HIGH_PRE.Properties.Minimum = 0;
            CMX_HIGH_PRE.Properties.Maximum = (int)Math.Abs(fValue * 100000);
        }

        private void CMX_MATRIX3_Click(object sender, EventArgs e)
        {
            m_nSelMatrix = 3;
            //var num = float.Parse(CMX_MATRIX3.Text) == 0 ? 4 : float.Parse(CMX_MATRIX3.Text);
            //SetCMX_HIGH_PREPro(num);
        }

        private void CMX_MATRIX6_Click(object sender, EventArgs e)
        {
            m_nSelMatrix = 6;
            //var num = float.Parse(CMX_MATRIX6.Text) == 0 ? 4 : float.Parse(CMX_MATRIX6.Text);
            //SetCMX_HIGH_PREPro(num);
        }

        private void CMX_MATRIX4_Click(object sender, EventArgs e)
        {
            m_nSelMatrix = 4;
            var num = float.Parse(CMX_MATRIX4.Text) == 0 ? 4 : float.Parse(CMX_MATRIX4.Text);
            SetCMX_HIGH_PREPro(num);
        }

        private void CMX_MATRIX7_Click(object sender, EventArgs e)
        {
            m_nSelMatrix = 7;
            var num = float.Parse(CMX_MATRIX7.Text) == 0 ? 4 : float.Parse(CMX_MATRIX7.Text);
            SetCMX_HIGH_PREPro(num);
        }

        private void CMX_MATRIX8_Click(object sender, EventArgs e)
        {
            m_nSelMatrix = 8;
            var num = float.Parse(CMX_MATRIX8.Text) == 0 ? 4 : float.Parse(CMX_MATRIX8.Text);
            SetCMX_HIGH_PREPro(float.Parse(CMX_MATRIX8.Text));
        }
        #endregion

        #region 滑动条设置值

        private void CMX_HIGH_PRE_EditValueChanged(object sender, EventArgs e)
        {
            int nPos = CMX_HIGH_PRE.Value;
            float fValue = nPos / 100000.0f;
            trackTxt.Text = fValue.ToString("f6");
            //bool bState;
            switch (m_nSelMatrix)
            {
                case 2:
                    {
                        if ((float.Parse(CMX_MATRIX2.Text) >= 0))
                        {
                            CMX_MATRIX2.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX2.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                case 3:
                    {
                        if ((float.Parse(CMX_MATRIX3.Text) >= 0))
                        {
                            CMX_MATRIX3.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX3.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                case 4:
                    {
                        if ((float.Parse(CMX_MATRIX4.Text) >= 0))
                        {
                            CMX_MATRIX4.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX4.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                case 6:
                    {
                        if ((float.Parse(CMX_MATRIX6.Text) >= 0))
                        {
                            CMX_MATRIX6.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX6.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                case 7:
                    {
                        if ((float.Parse(CMX_MATRIX7.Text) >= 0))
                        {
                            CMX_MATRIX7.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX7.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                case 8:
                    {
                        if ((float.Parse(CMX_MATRIX8.Text) >= 0))
                        {
                            CMX_MATRIX8.Text = trackTxt.Text;
                        }
                        else
                        {
                            CMX_MATRIX8.Text = (fValue * -1).ToString("f6");
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region 写寄存器
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="n">这个判断是数组下标 对应文本框</param>
        /// <param name="nLight">判断acd</param>
        void SetWriteMatrixRegister(int n, int nLight)
        {
            if (isRead) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            char mask = '\0';
            if (nLight == 1)//A
            {
                mask = 'A';
                switch (n)
                {
                    case 8:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[2, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[2, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[2, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 7:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[2, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[2, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[2, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 6:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[1, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[1, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[1, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 4:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[1, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[1, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[1, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 3:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[0, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[0, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[0, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 2:
                        {
                            var nIntpart = (int)(Math.Abs(m_fAMatrix[0, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fAMatrix[0, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fAMatrix[0, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    default:
                        break;
                }
                SetCmxRegister("Matrix_A", (ulong)m_nSymbol[0]);//SerialSend.WriteRegister(0x80300000 | 0x122F, (ulong)m_nSymbol[0], sPortTemp);
                SetCmxRegister("Matrix_A" + sceneMask, (ulong)m_nSymbol[0]);//SerialSend.WriteRegister(0x80300000 | 0x122F, (ulong)m_nSymbol[0], sPortTemp);
            }
            else if (nLight == 2)//C
            {
                mask = 'C';
                switch (n)
                {
                    case 8:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[2, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[2, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[2, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 7:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[2, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[2, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[2, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 6:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[1, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[1, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[1, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 4:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[1, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[1, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[1, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 3:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[0, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[0, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[0, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 2:
                        {
                            var nIntpart = (int)(Math.Abs(m_fCMatrix[0, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fCMatrix[0, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fCMatrix[0, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    default:
                        break;
                }
                SetCmxRegister("Matrix_C", (ulong)m_nSymbol[1]);
                SetCmxRegister("Matrix_C" + sceneMask, (ulong)m_nSymbol[1]);
            }
            else
            {//D
                mask = 'D';
                switch (n)
                {
                    case 8:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[2, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[2, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[2, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 7:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[2, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[2, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[2, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 6:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[1, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[1, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[1, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 4:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[1, 0]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[1, 0]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[1, 0]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 3:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[0, 2]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[0, 2]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[0, 2]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    case 2:
                        {
                            var nIntpart = (int)(Math.Abs(m_fDMatrix[0, 1]) * 1024) / 256;
                            SetCmxRegister($"Matrix_{mask}_{n}_h", (ulong)nIntpart);
                            SetCmxRegister($"Matrix_{mask}_{n}_h" + sceneMask, (ulong)nIntpart);
                            Thread.Sleep(5);
                            SetCmxRegister($"Matrix_{mask}_{n}_l", (ulong)(Math.Abs(m_fDMatrix[0, 1]) * 1024 - nIntpart * 256));
                            SetCmxRegister($"Matrix_{mask}_{n}_l" + sceneMask, (ulong)(Math.Abs(m_fDMatrix[0, 1]) * 1024 - nIntpart * 256));
                            Thread.Sleep(5);
                        }
                        break;
                    default:
                        break;
                }
                SetCmxRegister("Matrix_D", (ulong)m_nSymbol[2]);
                SetCmxRegister("Matrix_D" + sceneMask, (ulong)m_nSymbol[2]);
            }
        }

        #endregion

        #region 文本框编辑改变值

        private void CMX_MATRIX2_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 2;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[0, 1] = float.Parse(CMX_MATRIX2.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[0, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[0, 1] = -3.999999F;
                        }
                        m_fAMatrix[0, 0] = 1 - m_fAMatrix[0, 1] - m_fAMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fAMatrix[0, 0].ToString("f6");
                        if (m_fAMatrix[0, 1] >= 0)
                        {
                            m_nSymbol[0] |= 0x1;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xFE;
                        }
                        SetWriteMatrixRegister(2, 1);
                    }
                    break;
                case 1:
                    {

                        m_fCMatrix[0, 1] = float.Parse(CMX_MATRIX2.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[0, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[0, 1] = -3.999999F;
                        }
                        m_fCMatrix[0, 0] = 1 - m_fCMatrix[0, 1] - m_fCMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fCMatrix[0, 0].ToString("f6");
                        if (m_fCMatrix[0, 1] >= 0)
                        {
                            m_nSymbol[1] |= 0x1;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xFE;
                        }
                        SetWriteMatrixRegister(2, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[0, 1] = float.Parse(CMX_MATRIX2.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[0, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[0, 1] = -3.999999F;
                        }
                        m_fDMatrix[0, 0] = 1 - m_fDMatrix[0, 1] - m_fDMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fDMatrix[0, 0].ToString("f6");
                        if (m_fDMatrix[0, 1] >= 0)
                        {
                            m_nSymbol[2] |= 0x1;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xFE;
                        }
                        SetWriteMatrixRegister(2, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }

        private void CMX_MATRIX3_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 3;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[0, 2] = float.Parse(CMX_MATRIX3.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[0, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[0, 2] = -3.999999F;
                        }
                        m_fAMatrix[0, 0] = 1 - m_fAMatrix[0, 1] - m_fAMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fAMatrix[0, 0].ToString("f6");
                        if (m_fAMatrix[0, 2] >= 0)
                        {
                            m_nSymbol[0] |= 0x2;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xFD;
                        }
                        SetWriteMatrixRegister(3, 1);
                    }
                    break;
                case 1:
                    {
                        m_fCMatrix[0, 2] = float.Parse(CMX_MATRIX3.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[0, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[0, 2] = -3.999999F;
                        }
                        m_fCMatrix[0, 0] = 1 - m_fCMatrix[0, 1] - m_fCMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fCMatrix[0, 0].ToString("f6");
                        if (m_fCMatrix[0, 2] >= 0)
                        {
                            m_nSymbol[1] |= 0x2;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xFD;
                        }
                        SetWriteMatrixRegister(3, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[0, 2] = float.Parse(CMX_MATRIX3.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[0, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[0, 2] = -3.999999F;
                        }
                        m_fDMatrix[0, 0] = 1 - m_fDMatrix[0, 1] - m_fDMatrix[0, 2];
                        CMX_MATRIX1.Text = m_fDMatrix[0, 0].ToString("f6");
                        if (m_fDMatrix[0, 2] >= 0)
                        {
                            m_nSymbol[2] |= 0x2;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xFD;
                        }
                        SetWriteMatrixRegister(3, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }

        private void CMX_MATRIX6_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 6;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[1, 2] = float.Parse(CMX_MATRIX6.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[1, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[1, 2] = -3.999999F;
                        }
                        m_fAMatrix[1, 1] = 1 - m_fAMatrix[1, 0] - m_fAMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fAMatrix[1, 1].ToString("f6");
                        if (m_fAMatrix[1, 2] >= 0)
                        {
                            m_nSymbol[0] |= 0x8;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xF7;
                        }
                        SetWriteMatrixRegister(6, 1);
                    }
                    break;
                case 1:
                    {
                        m_fCMatrix[1, 2] = float.Parse(CMX_MATRIX6.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[1, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[1, 2] = -3.999999F;
                        }
                        m_fCMatrix[1, 1] = 1 - m_fCMatrix[1, 0] - m_fCMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fCMatrix[1, 1].ToString("f6");
                        if (m_fCMatrix[1, 2] >= 0)
                        {
                            m_nSymbol[1] |= 0x8;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xF7;
                        }
                        SetWriteMatrixRegister(6, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[1, 2] = float.Parse(CMX_MATRIX6.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[1, 2] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[1, 2] = -3.999999F;
                        }
                        m_fDMatrix[1, 1] = 1 - m_fDMatrix[1, 0] - m_fDMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fDMatrix[1, 1].ToString("f6");
                        if (m_fDMatrix[1, 2] >= 0)
                        {
                            m_nSymbol[2] |= 0x8;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xF7;
                        }
                        SetWriteMatrixRegister(6, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }

        private void CMX_MATRIX4_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 4;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[1, 0] = float.Parse(CMX_MATRIX4.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[1, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[1, 0] = -3.999999F;
                        }
                        m_fAMatrix[1, 1] = 1 - m_fAMatrix[1, 0] - m_fAMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fAMatrix[1, 1].ToString("f6");
                        if (m_fAMatrix[1, 0] >= 0)
                        {
                            m_nSymbol[0] |= 0x4;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xFB;
                        }
                        SetWriteMatrixRegister(4, 1);
                    }
                    break;
                case 1:
                    {
                        m_fCMatrix[1, 0] = float.Parse(CMX_MATRIX4.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[1, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[1, 0] = -3.999999F;
                        }
                        m_fCMatrix[1, 1] = 1 - m_fCMatrix[1, 0] - m_fCMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fCMatrix[1, 1].ToString("f6");
                        if (m_fCMatrix[1, 0] >= 0)
                        {
                            m_nSymbol[1] |= 0x4;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xFB;
                        }
                        SetWriteMatrixRegister(4, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[1, 0] = float.Parse(CMX_MATRIX4.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[1, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[1, 0] = -3.999999F;
                        }
                        m_fDMatrix[1, 1] = 1 - m_fDMatrix[1, 0] - m_fDMatrix[1, 2];
                        CMX_MATRIX5.Text = m_fDMatrix[1, 1].ToString("f6");
                        if (m_fDMatrix[1, 0] >= 0)
                        {
                            m_nSymbol[2] |= 0x4;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xFB;
                        }
                        SetWriteMatrixRegister(4, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }

        private void CMX_MATRIX7_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 7;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[2, 0] = float.Parse(CMX_MATRIX7.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[2, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[2, 0] = -3.999999F;
                        }
                        m_fAMatrix[2, 2] = 1 - m_fAMatrix[2, 0] - m_fAMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fAMatrix[2, 2].ToString("f6");
                        if (m_fAMatrix[2, 0] >= 0)
                        {
                            m_nSymbol[0] |= 0x10;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xEF;
                        }
                        SetWriteMatrixRegister(7, 1);
                    }
                    break;
                case 1:
                    {
                        m_fCMatrix[2, 0] = float.Parse(CMX_MATRIX7.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[2, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[2, 0] = -3.999999F;
                        }
                        m_fCMatrix[2, 2] = 1 - m_fCMatrix[2, 0] - m_fCMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fCMatrix[2, 2].ToString("f6");
                        if (m_fCMatrix[2, 0] >= 0)
                        {
                            m_nSymbol[1] |= 0x10;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xEF;
                        }
                        SetWriteMatrixRegister(7, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[2, 0] = float.Parse(CMX_MATRIX7.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[2, 0] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[2, 0] = -3.999999F;
                        }
                        m_fDMatrix[2, 2] = 1 - m_fDMatrix[2, 0] - m_fDMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fDMatrix[2, 2].ToString("f6");
                        if (m_fDMatrix[2, 0] >= 0)
                        {
                            m_nSymbol[2] |= 0x10;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xEF;
                        }
                        SetWriteMatrixRegister(7, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }

        private void CMX_MATRIX8_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text) | (txtEdit.Text == "-")) return;
            m_nSelMatrix = 8;
            switch (sewenRadio.SelectedIndex)
            {
                case 0:
                    {
                        m_fAMatrix[2, 1] = float.Parse(CMX_MATRIX8.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fAMatrix[2, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fAMatrix[2, 1] = -3.999999F;
                        }
                        m_fAMatrix[2, 2] = 1 - m_fAMatrix[2, 0] - m_fAMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fAMatrix[2, 2].ToString("f6");
                        if (m_fAMatrix[2, 1] >= 0)
                        {
                            m_nSymbol[0] |= 0x20;
                        }
                        else
                        {
                            m_nSymbol[0] &= 0xDF;
                        }
                        SetWriteMatrixRegister(8, 1);
                    }
                    break;
                case 1:
                    {
                        m_fCMatrix[2, 1] = float.Parse(CMX_MATRIX8.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fCMatrix[2, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fCMatrix[2, 1] = -3.999999F;
                        }
                        m_fCMatrix[2, 2] = 1 - m_fCMatrix[2, 0] - m_fCMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fCMatrix[2, 2].ToString("f6");
                        if (m_fCMatrix[2, 1] >= 0)
                        {
                            m_nSymbol[1] |= 0x20;
                        }
                        else
                        {
                            m_nSymbol[1] &= 0xDF;
                        }
                        SetWriteMatrixRegister(8, 2);
                    }
                    break;
                case 2:
                    {
                        m_fDMatrix[2, 1] = float.Parse(CMX_MATRIX8.Text);
                        if (float.Parse(txtEdit.Text) >= 4)
                        {
                            m_fDMatrix[2, 1] = 3.999999F;
                        }
                        if (float.Parse(txtEdit.Text) <= -4)
                        {
                            m_fDMatrix[2, 1] = -3.999999F;
                        }
                        m_fDMatrix[2, 2] = 1 - m_fDMatrix[2, 0] - m_fDMatrix[2, 1];
                        CMX_MATRIX9.Text = m_fDMatrix[2, 2].ToString("f6");
                        if (m_fDMatrix[2, 1] >= 0)
                        {
                            m_nSymbol[2] |= 0x20;
                        }
                        else
                        {
                            m_nSymbol[2] &= 0xDF;
                        }
                        SetWriteMatrixRegister(8, 3);
                    }
                    break;
                default:
                    break;
            }
            if (float.Parse(txtEdit.Text) >= 4)
            {
                isRead = true;
                txtEdit.Text = "3.999999";
                isRead = false;
            }
            if (float.Parse(txtEdit.Text) <= -4)
            {
                isRead = true;
                txtEdit.Text = "-3.999999";
                isRead = false;
            }
        }


        #endregion
        #region 初始化

        private void XChip_CMX_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
                this.Invoke((EventHandler)delegate {
                    CMX_HIGH_PRE.Properties.Minimum = 1;
                    CMX_HIGH_PRE.Properties.Maximum = 4 * 100000;
                    CMX_HIGH_PRE.Properties.SmallChange = 1;
                    for (int i = 0; i < XChipCMX.Count; i++)
                    {

                        var type = AppHelper.NameTypeToString(XChipCMX[i].NameType);
                        //加上单选框的_en
                        if (XChipCMX[i].ControlType == "1")
                        {
                            type = XChipCMX[i].NameType;
                        }
                        try
                        {
                            // Control col = this.Controls.Find(type, true)[0];
                            var col = this.Controls.Find(type, true);


                            foreach (var item in col)
                            {
                                if (item is TextEdit)
                                {
                                    //声明一个SuerToolTip
                                    DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                    //声明一个ToolTipTitleItem,保存标题
                                    DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                    String tooltips = "";

                                    if (!string.IsNullOrEmpty(XChipCMX[i].Bit_Wide))
                                    {
                                        tooltips += $"位宽={XChipCMX[i].Bit_Wide}";
                                    }
                                    if (!string.IsNullOrEmpty(XChipCMX[i].Bit_Accuracy))
                                    {
                                        tooltips += $"|精度={XChipCMX[i].Bit_Accuracy}";
                                    }
                                    //设置标题文字
                                    toolTipTitleItem.Text = tooltips;
                                    //把标题添加到SuerToolTip
                                    graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                    //指定控件的SuperTip

                                    ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                    //正则判断
                                    //((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                    //((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipCMX[i].Bits, XChipCMX[i].Bit_Wide, XChipCMX.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                });
            });
        }
        #endregion
        #region 勾选框changed

        private async void AUTO_FACTOR_EN_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (XChipCMX.Exists(c => c.NameType.ToLower() == chk.Name.ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == chk.Name.ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                SetCmxRegister(model, Val);
            }
            FactorGainShowHide(chk.Checked);
        }

        private async void CMX_AUTOCT_EN_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (XChipCMX.Exists(c => c.NameType.ToLower() == chk.Name.ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == chk.Name.ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                SetCmxRegister(model, Val);
            }
        }
        #endregion
        private async Task<long> GetCMXRegister(string nameType)
        {
            if (XChipCMX.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                long var = await ReadRegisterAsync(XChipCMX.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }

        }

        private void CMX_MAXFACTOR_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            var nValue = Convert.ToInt32(txtedit.Text, 16);
            if (nValue > 0x7f)
            {
                SetCmxRegister(txtedit.Name, ((ulong)0X7F));
                SetCmxRegister(txtedit.Name + sceneMask, ((ulong)0X7F));
                txtedit.Text = "7f"; return;
            }
            //SetCmxRegister("Max_factor", (((ulong)Convert.ToInt32(Max_factor.Text, 16)) & 0xff));
            //SetCmxRegister("Max_factor" + sceneMask, (((ulong)Convert.ToInt32(Max_factor.Text, 16)) & 0xff));

            if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetCmxRegister(model, Val);
            }
            if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}{sceneMask}".ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtedit.Name}{sceneMask}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetCmxRegister(model, Val);
            }
        }

        private void CMX_MINFACTOR_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return;
            if (string.IsNullOrEmpty(Min_factor.Text)) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            var nValue = Convert.ToInt32(Min_factor.Text, 16);
            if (nValue > 0x7f)
            {
                SetCmxRegister("Min_factor", ((ulong)0X7F));
                SetCmxRegister("Min_factor" + sceneMask, ((ulong)0X7F));
                Min_factor.Text = "7F"; return;
            }
            SetCmxRegister("Min_factor", (((ulong)Convert.ToInt32(Min_factor.Text, 16)) & 0xff));
            SetCmxRegister("Min_factor" + sceneMask, (((ulong)Convert.ToInt32(Min_factor.Text, 16)) & 0xff));
        }

        private void CMX_MAXGAIN_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //if (string.IsNullOrEmpty(Max_gain.Text)) return;
            //string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            //var nValue = Convert.ToInt32(Max_gain.Text, 16);
            //if (nValue > 0x1f)
            //{
            //    SetCmxRegister("Max_gain", ((ulong)0X1F));
            //    SetCmxRegister("Max_gain" + sceneMask, ((ulong)0X1F));
            //    Max_gain.Text = "1F"; return;
            //}
            //SetCmxRegister("Max_gain", (((ulong)Convert.ToInt32(Max_gain.Text, 16)) & 0xff));
            //SetCmxRegister("Max_gain" + sceneMask, (((ulong)Convert.ToInt32(Max_gain.Text, 16)) & 0xff));
            if (isWrite) return;
            if (isRead) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            var nValue = Convert.ToInt32(txtedit.Text, 16);
            if (nValue > 0x7f)
            {
                SetCmxRegister(txtedit.Name, ((ulong)0X1F));
                SetCmxRegister(txtedit.Name + sceneMask, ((ulong)0X1F));
                txtedit.Text = "1F"; return;
            }
            //SetCmxRegister("Max_factor", (((ulong)Convert.ToInt32(Max_factor.Text, 16)) & 0xff));
            //SetCmxRegister("Max_factor" + sceneMask, (((ulong)Convert.ToInt32(Max_factor.Text, 16)) & 0xff));

            if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetCmxRegister(model, Val);
            }
            if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}{sceneMask}".ToLower()))
            {
                var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtedit.Name}{sceneMask}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetCmxRegister(model, Val);
            }

        }

        private void CMX_MINGAIN_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return;
            if (string.IsNullOrEmpty(Min_gain.Text)) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            var nValue = Convert.ToInt32(Min_gain.Text, 16);
            if (nValue > 0x1f)
            {
                SetCmxRegister("Min_gain", ((ulong)0X1F));
                SetCmxRegister("Min_gain" + sceneMask, ((ulong)0X1F));
                Min_gain.Text = "1F"; return;
            }
            SetCmxRegister("Min_gain", (((ulong)Convert.ToInt32(Min_gain.Text, 16)) & 0xff));
            SetCmxRegister("Min_gain" + sceneMask, (((ulong)Convert.ToInt32(Min_gain.Text, 16)) & 0xff));
        }

        private void CMX_CTLIST2_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            string sceneMask = rdo_scene.SelectedIndex == 0 ? "_day" : "_night";
            var nValue = Convert.ToInt32(txtEdit.Text, 16);
            if (nValue > 0x3ff)
            {
                //SetCmxRegister("CT_list0_h", 0x03);
                //SetCmxRegister("CT_list0_l", 0xff);
                //SetCmxRegister("CT_list0_h" + sceneMask, 0x03);
                //SetCmxRegister("CT_list0_l" + sceneMask, 0xff);
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "3FF");
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "3FF");
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "3FF");
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "3FF");
                    SetCmxRegister(model, Val);
                }
                txtEdit.Text = "3FF";
            }
            else
            {
                //SetCmxRegister("CT_list0_h", ((ulong)(nValue >> 8) & 0xff));
                //SetCmxRegister("CT_list0_l", ((ulong)(nValue) & 0xff));
                //SetCmxRegister("CT_list0_h" + sceneMask, ((ulong)(nValue >> 8) & 0xff));
                //SetCmxRegister("CT_list0_l" + sceneMask, ((ulong)(nValue) & 0xff));
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetCmxRegister(model, Val);
                }
                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower()))
                {
                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetCmxRegister(model, Val);
                }
            }
            //switch (txtEdit.Tag.ToString())
            //{
            //    case "0":
            //        {
            //            if (nValue > 0x3ff)
            //            {
            //                SetCmxRegister("CT_list0_h", 0x03);
            //                SetCmxRegister("CT_list0_l", 0xff);
            //                SetCmxRegister("CT_list0_h" + sceneMask, 0x03);
            //                SetCmxRegister("CT_list0_l" + sceneMask, 0xff);
            //                txtEdit.Text = "3FF";
            //            }
            //            else
            //            {
            //                //SetCmxRegister("CT_list0_h", ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list0_l", ((ulong)(nValue) & 0xff));
            //                //SetCmxRegister("CT_list0_h" + sceneMask, ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list0_l" + sceneMask, ((ulong)(nValue) & 0xff));
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //            }
            //        }
            //        break;
            //    case "1":
            //        {
            //            if (nValue > 0x3ff)
            //            {
            //                SetCmxRegister("CT_list1_h", 0x03);
            //                SetCmxRegister("CT_list1_l", 0xff);
            //                SetCmxRegister("CT_list1_h" + sceneMask, 0x03);
            //                SetCmxRegister("CT_list1_l" + sceneMask, 0xff);
            //                txtEdit.Text = "3FF";
            //            }
            //            else
            //            {
            //                //SetCmxRegister("CT_list1_h", ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list1_l", ((ulong)(nValue) & 0xff));
            //                //SetCmxRegister("CT_list1_h" + sceneMask, ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list1_l" + sceneMask, ((ulong)(nValue) & 0xff));
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //            }
            //        }
            //        break;
            //    case "2":
            //        {
            //            if (nValue > 0x3ff)
            //            {
            //                SetCmxRegister("CT_list2_h", 0x03);
            //                SetCmxRegister("CT_list2_l", 0xff);
            //                SetCmxRegister("CT_list2_h" + sceneMask, 0x03);
            //                SetCmxRegister("CT_list2_l" + sceneMask, 0xff);
            //                txtEdit.Text = "3FF";
            //            }
            //            else
            //            {
            //                //SetCmxRegister("CT_list2_h", ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list2_l", ((ulong)(nValue) & 0xff));
            //                //SetCmxRegister("CT_list2_h" + sceneMask, ((ulong)(nValue >> 8) & 0xff));
            //                //SetCmxRegister("CT_list2_l" + sceneMask, ((ulong)(nValue) & 0xff));
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_h{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //                if (XChipCMX.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower()))
            //                {
            //                    var model = XChipCMX.Find(c => c.NameType.ToLower() == $"{txtEdit.Name}_l{sceneMask}".ToLower());
            //                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
            //                    SetCmxRegister(model, Val);
            //                }
            //            }
            //        }
            //        break;
            //    default:
            //        break;
            //}
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            //SaveFileDialog sfd = new SaveFileDialog();
            ////设置文件类型 
            //sfd.Filter = "配置文件（*.txt）|*.txt";

            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;

            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //sfd.FileName = "IQ_Setting_CMX_" + DateTime.Now.ToString("yyyyMMddHHmms");
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
            //    //StringBuilder sb = new StringBuilder();
            //    var Pe_dal = new parameter_exportManager();
            //    if (null != Pe_dal)
            //    {
            //        WaitBefore.Start("参数导出", "正在加载中", 60);
            //        var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "CMX" || c.Module.Contains("cmx 0x80301200")).OrderBy(c => c.SortNum).ToList();
            //        #region 判断是否需要用白天的数据
            //        var Pe_patch_dal = new parameter_export_patchManager();
            //        var patchList = Pe_patch_dal.GetList();
            //        var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
            //        foreach (var item in conditionList)
            //        {
            //            if (IsUsbOpen)
            //            {
            //                uint pVule = 0x0;
            //                XChipUSB.UsbRegisterRead64(Convert.ToUInt32(item, 16), ref pVule, false);
            //                if (pVule == 0)
            //                {
            //                    patchList.RemoveAll(c => c.ConditionAddr == item);
            //                }
            //            }
            //            else
            //            {
            //                if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
            //                {
            //                    patchList.RemoveAll(c => c.ConditionAddr == item);
            //                }
            //            }

                       
            //        }
            //        #endregion

            //        var sb = XChipHelp.ReadParameterExportExpandUSB(tempList, "80", patchList, sPortTemp);

            //        System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
            //        WaitBefore.Close();
            //        DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            //    }
            //}
        }

        private void CMX_MAXFACTOR_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CMX_MAXFACTOR_Leave(sender, null);
            }
        }

        private void CMX_MINFACTOR_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CMX_MINFACTOR_Leave(sender, null);
            }
        }

        private void CMX_MAXGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CMX_MAXGAIN_Leave(sender, null);
            }
        }

        private void CMX_MINGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CMX_MINGAIN_Leave(sender, null);
            }
        }

        private void CMX_CTLIST2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CMX_CTLIST2_Leave(sender, null);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       在高、中、低3个色温下，调节对应色温的CMX校正矩阵；当Auto CT功能关闭（未勾选）时，所有场景都采用D light下的校正矩阵，当使能Auto CT（勾选上）功能时，当前CMX校正矩阵是通过当前色温值所在的位置，由相邻2个CMX矩阵插值而来。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()
        {
            //string str = "       在高、中、低3个色温下，调节对应色温的CMX校正矩阵；当Auto CT功能关闭（未勾选）时，所有场景都采用D light下的校正矩阵，当使能Auto CT（勾选上）功能时，当前CMX校正矩阵是通过当前色温值所在的位置，由相邻2个CMX矩阵插值而来。\r\n       更多详见《调试工具用户手册》。";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("CMX调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private async void btn_Get_scene_Click(object sender, EventArgs e)
        {
            isRead = true;
            long nMask = await GetCMXRegister("cur_scene_nIdx") & 0x03;
            if (nMask == 0)
            {
                rdo_scene.SelectedIndex = 0;
            }
            else /*if (nMask == 1)*/
            {
                rdo_scene.SelectedIndex = 1;
            }
            //else if (nMask == 2)
            //{
            //    AE_radiomode.SelectedIndex = 2;
            //}
            //Scene_Switch_En
            if ((await GetCMXRegister("nEffectSceneMode") == 0x12))
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }
            //Debug_En
            if ((await GetCMXRegister("nSwitchMode") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    rdo_scene.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                rdo_scene.Enabled = false;
            }
            isRead = false;
        }

        private void rdo_scene_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;

            if (aeradio.EditValue.ToString() == "1")
            {
                SetCmxRegister("cur_scene_nIdx", 0x00);
            }
            else if (aeradio.EditValue.ToString() == "2")
            {
                SetCmxRegister("cur_scene_nIdx", 0x01);
            }
            else if (aeradio.EditValue.ToString() == "3")
            {
                SetCmxRegister("cur_scene_nIdx", 0x02);
            }

            Thread.Sleep(50);
            //SerialSend.WriteRegister(0x80140a8f, 0x01, sPortTemp);

            simpleButton5_Click(null, null);
        }

        private async void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;

            //Scence Switch En 
            var nTemp1 = await GetCMXRegister("nEffectSceneMode");
            // Debug en
            var nTemp2 = await GetCMXRegister("nSwitchMode");
            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 | 0x04));
                SetCmxRegister("nEffectSceneMode", 0x12);
                checkedListBoxControl1.Items[1].Enabled = true;
                if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else  //S不勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 & 0xfb));
                SetCmxRegister("nEffectSceneMode", 0x00);
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }


            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
            {
                //

                SetCmxRegister("nSwitchMode", (ulong)(nTemp2 & 0xfd));
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else//D不勾选
            { //

                SetCmxRegister("nSwitchMode", (ulong)(nTemp2 | 0x02));
                rdo_scene.Enabled = false;
            }
        }


        private void simpleButton5_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton5_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }
    }
}